<!--垃圾清运-->
<template>
  <div class="CheckInBysave">
    <!--头部bar开始-->
    <CommonBar :options="options"></CommonBar>
    <!--头部bar结束-->
    <!--表格-->
    <div class="punchdiv">
      <!--未打卡开始-->
      <div v-if="shangbandakashow" class="textcenter">
        <button
          class="punchcontent"
          :class="workbutton?'punchcontent1':''"
          @click="workbut"
          :disabled="workbutton"
        >
          <div>
            <p class="title">垃圾清运</p>
          </div>
        </button>
        <p class="punchmap">
          <van-icon name="checked" :class="workbutton?'checkedicon1':''" class="checkedicon" />
          <span>{{areadesc}}</span>
        </p>
      </div>
      <!--未打卡结束-->
    </div>
    <div id="area"></div>
  </div>
</template>
<script>
import BMap from "BMap";
import CommonBar from "../common/commonBar";
import { mapState } from "vuex";
export default {
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization
    })
  },
  data() {
    return {
      options: {
        type: "icon",
        centerText: "垃圾清运",
        iconNname: "wap-home",
        lefttype: "left"
      },
      List: [],
      bmap: null,
      duty_area: [],
      shangbandakashow: true, //上班打卡的两步
      workbutton: true, //上班打卡按钮
      areadesc: "未进入责任范围",
      currentLng: "",
      currentLat: "",
      translateCallback: ""
    };
  },

  mounted() {
    //获取gps坐标
    var that = this;
    // document.addEventListener("deviceready", that.getposition, false);
    that.getLoadData();
  },
  methods: {
    //考核列表
    getLoadData() {
      this.$toast.loading({
        mask: true,
        message: "加载中...",
        duration: 5000
      });
      var params = {
        token: this.token
      };
      this.$http
        .get(
          `${this.$basePath}?service=App.Attendance.InfoCheckInByScavenging&api=88`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            this.$toast.clear();
            console.log(res);
            if (typeof res.data.WGS84 == "string") {
              this.duty_area = JSON.parse(res.data.WGS84);
            }
            console.log(this.duty_area);
            this.$nextTick(() => {
              this.getposition();
            });
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    CheckInByHead(params) {
      this.$toast.loading({
        mask: true,
        message: "加载中...",
        duration: 5000
      });

      this.$http
        .get(
          `${this.$basePath}?service=App.Attendance.CheckInByScavenging&api=88`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            this.$toast.clear();
            this.workbutton = true;
            setTimeout(() => {
              this.workbutton = false;
            }, 660000);
            this.$toast({ message: "操作成功" });
          } else {
            this.$toast({ message: res.msg });
          }
        });
    },
    //上班打卡
    workbut() {
      var that = this;
      var geolocation = new BMap.Geolocation();
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function(r) {
        var latitude = String(r.point.lat);
        var longitude = String(r.point.lng);

        var params = {
          token: that.token,
          workplace: { lon: longitude, lat: latitude }
        };

        //workplace: { lon: "112.6304654928409", lat: "33.2999248775004634" }
        console.log(params);
        that.CheckInByHead(params);
      });
    },
    //地图
    initBmap(Lng, Lat) {
      var that = this;
      that.bmap = new BMap.Map("area", { drawer: BMAP_SVG_DRAWER });
      that.bmap.enableScrollWheelZoom(); // 开启鼠标滚轮缩放
      that.bmap.addControl(new BMap.ScaleControl()); // 添加比例尺控件
      //标位置点
      if (Lng || Lat) {
        var point1 = new BMap.Point(Lng, Lat);
        var markergg1 = new BMap.Marker(point1);
        that.bmap.addOverlay(markergg1); //添加GPS marker
        var labelgg1 = new BMap.Label("原始坐标", {
          offset: new BMap.Size(20, -10)
        });
        //转换坐标
        that.translateCallback = function(data) {
          console.log(111111);
          if (data.status === 0) {
            console.log("转换后的百度坐标", data.points[0]);
            var translng = data.points[0].lng;
            var translat = data.points[0].lat;
            var marker = new BMap.Marker(data.points[0]);
            that.bmap.addOverlay(marker);
            var label = new BMap.Label("转换后的百度坐标（正确）", {
              offset: new BMap.Size(20, -10)
            });
            marker.setLabel(label); //添加百度label
            that.bmap.setCenter(data.points[0]);

            // 画垃圾区域
            var trackPoint = [];
            if (that.duty_area != null) {
              for (var i = 0, j = that.duty_area.length; i < j; i++) {
                trackPoint.push(
                  new BMap.Point(that.duty_area[i].lng, that.duty_area[i].lat)
                );
              }
              that.bmap.centerAndZoom(trackPoint[0], 13);
              var polyline = new BMap.Polygon(trackPoint, {
                strokeColor: "red",
                strokeWeight: 3,
                strokeOpacity: 1
              });
              that.bmap.addOverlay(polyline);
              //判断当前坐标是否在区域内
              // var pt = new BMap.Point(translng, translat); //这是当前坐标
              // //var pt = new BMap.Point(112.6304654928409, 33.2999248775004634);
              // that.bmap.addOverlay(new BMap.Marker(pt));
              // console.log(pt);
              if (BMapLib.GeoUtils.isPointInPolygon(marker, polyline)) {
                console.log("已进入");
                //如果点在区域内，返回true
                // that.$toast({ message: "已进入责任范围" });
                // that.bmap.addOverlay(new BMap.Marker(pt));
                that.workbutton = false;
                that.areadesc = "已进入责任范围";
              } else {
                // that.$toast({ message: "未进入责任范围" });
                // that.bmap.addOverlay(new BMap.Marker(pt));
                console.log("未进入");
                that.workbutton = true;
                that.areadesc = "未进入责任范围";
              }
            } else {
              that.$toast({ message: "未划分垃圾站" });
              return;
            }
          }
        };
        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(point1);
        convertor.translate(pointArr, 1, 5, that.translateCallback);
      } else {
        that.$toast({ message: "无法获取坐标" });
      }
    },
    //获取坐标
    getposition() {
      var that = this;
      console.log(111);
      navigator.geolocation.getCurrentPosition(
        function(position) {
          var currentLat = position.coords.latitude;
          var currentLng = position.coords.longitude;
          console.log("经度", currentLng, "纬度", currentLat);
          that.initBmap(currentLng, currentLat);
        },
        function(error) {
          console.log(error.message, "温馨提示");
        }
      );
    }
  }
};
</script>
<style lang="less" scoped>
#area {
  // width: 100%;
  // height: 500px;
}

.punchdiv {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 100px);
  width: 100%;
  min-height: 150px;
  .textcenter {
    text-align: center;
  }
  .punchcontent {
    width: 140px;
    height: 140px;
    border-radius: 100%;
    background: url(../../../static/image/kaoqin_icon.png) no-repeat;
    // background: rgba(60, 211, 168, 1);
    // box-shadow: 0px 4px 13px 0px rgba(32, 177, 136, 0.5);
    background-size: 100% 100%;
    margin: 0 auto;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    outline: none;
    border: none;
    .title {
      font-size: 18px;
      margin: 0 0 5px;
    }
    .time {
      font-size: 14px;
      margin: 0;
    }
  }
  .punchcontent1 {
    background: url(../../../static/image/kaoqin_iconhui.png) no-repeat;
    background-size: 100% 100%;
  }
  .checkedicon {
    font-size: 14px;
    vertical-align: middle;
    color: #15bc83;
  }
  .punchmap {
    font-size: 14px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: rgba(150, 150, 150, 1);
  }
}
.checkedicon1 {
  color: #999 !important;
}
</style>